#include "stm32f10x.h"                  // Device header



/*初始化PWM*/
void PWM_Init(void)
{
	// 打开时钟
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);			//开启定时器TIM2的时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	
	// 配置时钟源
	TIM_InternalClockConfig(TIM2);									// 别忘了
	
	// 时基单元
	TIM_TimeBaseInitTypeDef Timer2_BaseInitStruture;
	TIM_TimeBaseStructInit(&Timer2_BaseInitStruture);				// 默认配置,下面手动修改
	Timer2_BaseInitStruture.TIM_ClockDivision = TIM_CKD_DIV1;
	Timer2_BaseInitStruture.TIM_CounterMode = TIM_CounterMode_Up;
	Timer2_BaseInitStruture.TIM_Period = 20000 - 1;					// ARR
	Timer2_BaseInitStruture.TIM_Prescaler = 72 - 1;					// PSC
//	Timer2_BaseInitStruture.TIM_RepetitionCounter = 0; 				// 高级定时器的功能
	TIM_TimeBaseInit(TIM2, &Timer2_BaseInitStruture);
	TIM_Cmd(TIM2, ENABLE);											// 打开TIM2定时器
	
	// OC输出比较单元
	TIM_OCInitTypeDef TIM2_OCInitStruture;
	TIM_OCStructInit(&TIM2_OCInitStruture);
	TIM2_OCInitStruture.TIM_OCMode = TIM_OCMode_PWM1;
	TIM2_OCInitStruture.TIM_OCPolarity = TIM_OCPolarity_High;
	TIM2_OCInitStruture.TIM_OutputState = TIM_OutputState_Enable;
	TIM2_OCInitStruture.TIM_Pulse = 0;								// CCR  (占空比)
	TIM_OC2Init(TIM2, &TIM2_OCInitStruture);						// 使用TIM2的CH2输出
	
	// GPIO配置
	GPIO_InitTypeDef GPIO_InitStruture;
	GPIO_InitStruture.GPIO_Mode = GPIO_Mode_AF_PP;					// 复用
	GPIO_InitStruture.GPIO_Pin = GPIO_Pin_1;
	GPIO_InitStruture.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStruture);
}



/*调控PWM的占空比*/
void PWM_SetPulse(uint16_t pulse)
{
	TIM_SetCompare2(TIM2, pulse);
}
